package guestbook;

import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.MessageType;
import com.google.appengine.api.xmpp.SendResponse;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Logger;

/**
 * @author Alejandro Gomez (alejandro.gomez@fdvsolutions.com)
 *         Date: 8/17/11
 *         Time: 5:36 PM
 */
public class MessageChatServlet extends HttpServlet {

    private static final Logger LOG = Logger.getLogger(MessageChatServlet.class.getName());

    protected void doPost(HttpServletRequest _request, HttpServletResponse _response) throws ServletException, IOException {
        final XMPPService xmppService = XMPPServiceFactory.getXMPPService();
        Message message = xmppService.parseMessage(_request);
        LOG.info("New msg from: " + message.getFromJid() + " - to: " + message.getRecipientJids()[0] + " - body: " + message.getBody());
        LOG.info("New msg stanza: " + message.getStanza());

        if (xmppService.getPresence(message.getFromJid()).isAvailable()) {
            LOG.info("usuario disponible");
            final MessageBuilder messageBuilder = new MessageBuilder();
            messageBuilder.withMessageType(MessageType.CHAT)
                    .withBody("Echo: " + message.getBody())
                    .withRecipientJids(message.getFromJid())
                    .withFromJid(message.getRecipientJids()[0]);
            SendResponse response = xmppService.sendMessage(messageBuilder.build());
            boolean messageSent = (response.getStatusMap().get(message.getFromJid()) == SendResponse.Status.SUCCESS);
            LOG.info("mensaje enviado success: " + messageSent);
        }
    }
}
